#include <memory>
#include <cstdio>
#include <vector>

#include "UdpServer.hpp"

void Usege(char* proc)
{
    std::cout<<"\n\tUsage: "<<proc<<"port[1024+]\n"<<std::endl;
}

std::string Handler(std::string str)
{
    std::string res = "Server get a message ";
    res += str; 
    return res;
}

bool SafeCheck(const std::string& cmd)
{
    // 搞一个vector的数组，然后遍历它，进行find查找
    vector<string> check = {
        "rm",
        "mv",
        "cp",
        "kill",
        "sudo",
        "unlink",
        "uninstall",
        "yum",
        "top",
        "while"
    };
    for(const auto& ch : check)
    {
        auto pos = cmd.find(ch);
        if(pos != std::string::npos) return false;
    }
    return true;
}

// 理解远端指令是怎么一回事
std::string ExcuteCommand(const std::string& cmd)
{
    std::cout<<"cmd:" << cmd << std::endl;
    // 根据SafeCheck函数做安全检查
    if(!SafeCheck(cmd)) return "error";

    // 建立好管道
    // 创建子进程
    // 子进程执行的结果通过管道交给父进程
    // 父进程想读到执行结果可以在FILE*指针也就是fp中读到
    FILE* fp = popen(cmd.c_str(),"r");

    if(fp == nullptr)
    {
        perror("popen");
        return "error";
    }
    std::string result;
    char buffer[4096];
    while(true)
    {
        char* res = fgets(buffer,sizeof(buffer),fp);
        if(res == nullptr) break;
        result += buffer;
    }

    pclose(fp);
    return result;
}

int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        Usege(argv[0]);
        exit(1);
    }

    uint16_t port = std::stoi(argv[1]);
    std::unique_ptr<UdpServer> svr(new UdpServer(port));

    svr->Init();
    svr->Run(/*ExcuteCommand*/);

    return 0; 
}